package com.bestom.bluetoothlock.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bestom.bluetoothlock.LockApplication;
import com.bestom.bluetoothlock.R;
import com.bestom.bluetoothlock.adapter.SearchDeviceListAdapter;
import com.bestom.bluetoothlock.bluetooth.BleServiceManage;
import com.bestom.bluetoothlock.bluetooth.BraceletInstructions;
import com.bestom.bluetoothlock.entity.BleInfo;
import com.bestom.bluetoothlock.entity.EventDevice;
import com.bestom.bluetoothlock.entity.ReceiveInfo;
import com.bestom.bluetoothlock.util.Constants;
import com.bestom.bluetoothlock.util.CurrencyDataManage;
import com.bestom.bluetoothlock.util.LogUtils;
import com.bestom.bluetoothlock.util.ToastUtil;
import com.bestom.bluetoothlock.views.InputDialog;
import com.bestom.bluetoothlock.views.SearchDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchDeviceActivity extends BaseActivity {
    /* access modifiers changed from: private */
    public SearchDeviceListAdapter adapter;
    /* access modifiers changed from: private */
    public BleServiceManage bleManage;
    /* access modifiers changed from: private */
    public SearchDialog dialog;
    @SuppressLint("HandlerLeak")
    private Handler handlerListen = new Handler() {
        public void handleMessage(Message message) {
            super.handleMessage(message);
            int i = message.what;
            if (i != 0) {
                switch (i) {
                    case 2:
                        SearchDeviceActivity.this.dismissDialog();
                        if (!LockApplication.getSharedPreferencesHelper().getBoolean("registered_" + CurrencyDataManage.getInstance().getCurrentBleDevice().getLockmac())) {
                            SearchDeviceActivity.this.mPasswordDialog.show();
                            return;
                        }
                        int i2 = LockApplication.getSharedPreferencesHelper().getInt("count");
                        boolean z = false;
                        if (i2 > 0) {
                            int i3 = 0;
                            while (true) {
                                if (i3 < i2) {
                                    if (LockApplication.getSharedPreferencesHelper().getString("mac" + i3).equals(CurrencyDataManage.getInstance().getCurrentBleDevice().getLockmac())) {
                                        z = true;
                                    } else {
                                        i3++;
                                    }
                                }
                            }
                        }
                        if (!z) {
                            SearchDeviceActivity searchDeviceActivity = SearchDeviceActivity.this;
                            searchDeviceActivity.showInputDialog(searchDeviceActivity.getString(R.string.change_device_name));
                            return;
                        }
                        Intent intent = new Intent(SearchDeviceActivity.this, DeviceFunctionActivity.class);
                        intent.putExtra(Constants.KEY_VALUE, CurrencyDataManage.getInstance().getCurrentBleDevice());
                        SearchDeviceActivity.this.startActivity(intent);
                        SearchDeviceActivity.this.finish();
                        return;
                    case 3:
                        Log.d("agui", "BLE_NOTIFY_VALUE........");
                        ReceiveInfo receiveInfo = (ReceiveInfo) message.obj;
                        String cmd = receiveInfo.getCmd();
                        String result = receiveInfo.getResult();
                        if (cmd == null) {
                            return;
                        }
                        if ((cmd.equals(BraceletInstructions.INSTRUCTIONS_FINGER_NUMBER) || cmd.equals(BraceletInstructions.INSTRUCTIONS_SET_PASSWORD)) && result != null && result.equals("00")) {
                            SearchDeviceActivity.this.dismissDialog();
                            SearchDeviceActivity.this.bleManage.setRegistered(true);
                            if (!LockApplication.getSharedPreferencesHelper().getBoolean("registered_" + CurrencyDataManage.getInstance().getCurrentBleDevice().getLockmac())) {
                                LockApplication.getSharedPreferencesHelper().saveBoolean("registered_" + CurrencyDataManage.getInstance().getCurrentBleDevice().getLockmac(), true);
                            }
                            SearchDeviceActivity.this.mHandler.removeMessages(1);
                            SearchDeviceActivity.this.mHandler.removeMessages(2);
                            SearchDeviceActivity.this.mHandler.removeMessages(3);
                            SearchDeviceActivity.this.mHandler.sendEmptyMessageDelayed(3, 500);
                            return;
                        }
                        return;
                    default:
                        return;
                }
            } else {
                SearchDeviceActivity.this.dismissDialog();
                BleInfo bleInfo = (BleInfo) message.obj;
                Log.d("agui", "notifyDataSetChanged........");
                SearchDeviceActivity.this.adapter.notifyDataSetChanged();
            }
        }
    };
    @BindView(R.id.iv_left)
    ImageView iv_left;
    @BindView(R.id.iv_right)
    ImageView iv_right;
    /* access modifiers changed from: private */
    public List<BleInfo> list;
    @BindView(R.id.search_device_list)
    ListView listView;
    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message message) {
            super.handleMessage(message);
            switch (message.what) {
                case 1:
                    SearchDeviceActivity.this.bleManage.setRegistered(true);
                    SearchDeviceActivity.this.bleManage.sendData(BraceletInstructions.getFingerNumberInstructions());
                    SearchDeviceActivity.this.mHandler.sendEmptyMessageDelayed(2, 2000);
                    return;
                case 2:
                    SearchDeviceActivity.this.dismissDialog();
                    SearchDeviceActivity searchDeviceActivity = SearchDeviceActivity.this;
                    ToastUtil.toast(searchDeviceActivity.getResources().getString(R.string.password_incorrect));
                    return;
                case 3:
                    Log.d("agui", "AddToFile........");
                    SearchDeviceActivity.this.AddToFile();
                    SearchDeviceActivity searchDeviceActivity2 = SearchDeviceActivity.this;
                    searchDeviceActivity2.showInputDialog(searchDeviceActivity2.getString(R.string.change_device_name));
                    return;
                default:
                    return;
            }
        }
    };
    private EditText mInputEdit;
    /* access modifiers changed from: private */
    public Dialog mPasswordDialog;
    private EditText mVerifyEdit;
    @BindView(R.id.tv_title)
    TextView tv_title;

    /* access modifiers changed from: protected */
    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView((int) R.layout.activity_search_device);
        ButterKnife.bind(this);
        initView();
        View inflate = View.inflate(this, R.layout.password, (ViewGroup) null);
        this.mInputEdit = (EditText) inflate.findViewById(R.id.inputEdit);
        this.mVerifyEdit = (EditText) inflate.findViewById(R.id.verifyEdit);
        this.mPasswordDialog = new AlertDialog.Builder(this, R.style.AlertDialog).setView(inflate).create();
        if (Build.VERSION.SDK_INT >= 23 && checkSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE") == -1) {
            requestPermissions(new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"}, 135);
        }
    }

    /* access modifiers changed from: private */
    public void AddToFile() {
        try {
            String str = Environment.getExternalStoragePublicDirectory("") + "/";
            File file = new File(str);
            if (!file.exists()) {
                file.mkdir();
            }
            FileWriter fileWriter = new FileWriter(str + "locksus.txt", true);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            Calendar instance = Calendar.getInstance();
            System.out.println("Current time => " + instance.getTime());
            bufferedWriter.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(instance.getTime()));
            bufferedWriter.append(CurrencyDataManage.getInstance().getCurrentBleDevice().getLockmac());
            bufferedWriter.write(" ");
            bufferedWriter.append(LockApplication.getSharedPreferencesHelper().getString("password_" + CurrencyDataManage.getInstance().getCurrentBleDevice().getLockmac()));
            bufferedWriter.write("\r\n");
            bufferedWriter.close();
            fileWriter.close();
            Intent intent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
            intent.setData(Uri.fromFile(new File(str + "locksus.txt")));
            sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        this.tv_title.setText(getString(R.string.search_device));
        this.iv_left.setVisibility(View.VISIBLE);
        this.iv_right.setVisibility(View.VISIBLE);
        this.iv_right.setImageResource(R.drawable.iv_updata_icon);
        this.bleManage = BleServiceManage.getInstance(this);
        this.bleManage.setHandlerListener(this.handlerListen);
        this.list = this.bleManage.service.bleInfos;
        this.adapter = new SearchDeviceListAdapter(this);
        List<BleInfo> list2 = this.list;
        if (list2 != null) {
            this.adapter.setData(list2);
            this.listView.setAdapter(this.adapter);
        }
        this.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
                SearchDeviceActivity.this.showConnectDialog();
                SearchDeviceActivity.this.bleManage.connect(SearchDeviceActivity.this.list.get(i).getAddress());
            }
        });
    }

    public void OnSaveNameDoneClicked(View view) {
        String obj = this.mInputEdit.getText().toString();
        if (obj.equals("") || obj.length() != 6) {
            Toast.makeText(this, getResources().getString(R.string.please_input_password), 1).show();
            return;
        }
        String obj2 = this.mVerifyEdit.getText().toString();
        if (obj2.equals("")) {
            Toast.makeText(this, getResources().getString(R.string.please_verify_password), 1).show();
        } else if (!obj.equals(obj2)) {
            Toast.makeText(this, getResources().getString(R.string.please_verify_password), 1).show();
        } else {
            LogUtils.i("agui", "start write password");
            LockApplication.getSharedPreferencesHelper().saveString("password_" + CurrencyDataManage.getInstance().getCurrentBleDevice().getLockmac(), obj);
            this.mPasswordDialog.dismiss();
            showConnectDialog();
            this.bleManage.setPassword(obj);
            try {
                this.bleManage.sendData(BraceletInstructions.setPasswordInstructions(obj));
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.mHandler.removeMessages(1);
            this.mHandler.sendEmptyMessageDelayed(1, 2000);
        }
    }

    /* access modifiers changed from: private */
    public void showInputDialog(String str) {
        final InputDialog inputDialog = new InputDialog(this);
        inputDialog.show();
        inputDialog.setTitle(str);
        inputDialog.setOnConfirmClickListener(new InputDialog.OnConfirmClickListener() {
            public void onConfirmClick(View view) {
                String content = inputDialog.getContent();
                if (TextUtils.isEmpty(content)) {
                    ToastUtil.toast(SearchDeviceActivity.this.getString(R.string.please_input_device_name));
                    return;
                }
                int i = LockApplication.getSharedPreferencesHelper().getInt("count");
                boolean z = false;
                if (i > 0) {
                    int i2 = 0;
                    while (true) {
                        if (i2 >= i) {
                            break;
                        }
                        if (LockApplication.getSharedPreferencesHelper().getString("mac" + i2).equals(CurrencyDataManage.getInstance().getCurrentBleDevice().getLockmac())) {
                            z = true;
                            break;
                        }
                        i2++;
                    }
                }
                if (!z) {
                    LockApplication.getSharedPreferencesHelper().saveString("mac" + i, CurrencyDataManage.getInstance().getCurrentBleDevice().getLockmac());
                    LockApplication.getSharedPreferencesHelper().saveInt("count", i + 1);
                    SearchDeviceActivity searchDeviceActivity = SearchDeviceActivity.this;
                    searchDeviceActivity.showInputDialog(searchDeviceActivity.getString(R.string.change_device_name));
                }
                LockApplication.getSharedPreferencesHelper().saveString("name_" + CurrencyDataManage.getInstance().getCurrentBleDevice().getLockmac(), content);
                EventBus.getDefault().post(new EventDevice(1));
                Intent intent = new Intent(SearchDeviceActivity.this, DeviceFunctionActivity.class);
                intent.putExtra(Constants.KEY_VALUE, CurrencyDataManage.getInstance().getCurrentBleDevice());
                SearchDeviceActivity.this.startActivity(intent);
                SearchDeviceActivity.this.finish();
            }
        });
    }

    private void showSearchDialog() {
        if (!this.bleManage.checkBLEenable()) {
            ToastUtil.toast(getString(R.string.please_open_bluetooth));
            return;
        }
        if (this.dialog == null) {
            this.dialog = new SearchDialog(this);
        }
        this.dialog.show();
        this.dialog.setTitle(getString(R.string.are_the_search));
        Window window = this.dialog.getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.width = -1;
        window.setAttributes(attributes);
        this.bleManage.startScan();
        new Handler().postDelayed(new Runnable() {
            public void run() {
                SearchDeviceActivity.this.dialog.dismiss();
                SearchDeviceActivity.this.bleManage.stopScan();
            }
        }, 5000);
    }

    /* access modifiers changed from: private */
    public void showConnectDialog() {
        if (this.dialog == null) {
            this.dialog = new SearchDialog(this);
        }
        this.dialog.show();
        this.dialog.setTitle(getString(R.string.connecting));
        Window window = this.dialog.getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.width = -1;
        window.setAttributes(attributes);
    }

    /* access modifiers changed from: private */
    public void dismissDialog() {
        SearchDialog searchDialog = this.dialog;
        if (searchDialog != null) {
            searchDialog.dismiss();
        }
    }

    @OnClick({R.id.iv_left, R.id.iv_right})
    public void onClickView(View view) {
        int id = view.getId();
        if (id == R.id.iv_left) {
            finish();
        } else if (id == R.id.iv_right) {
            showSearchDialog();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}